<template>
  <el-dialog
    :title="$t('msg.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="closed"
  >
    <el-checkbox-group v-model="userRoleTitleList">
      <el-checkbox
        v-for="item in roleList"
        :key="item.id"
        :label="item.title"
        :value="item.id"
      ></el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.universal.cancel') }}</el-button>
        <el-button @click="onConfirm" type="primary">{{
          $t('msg.universal.confirm')
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import { getRoleList } from '@/api/role.js'
import { watchSwitchLang } from '@/utils/i18n'
import { userRoles, updateUserRoles } from '@/api/user-manage'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  userId: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['update:modelValue', 'updateRoles'])

const closed = () => {
  emits('update:modelValue', false)
}

const i18n = useI18n()
const onConfirm = async () => {
  console.log('userRoleTitleList', userRoleTitleList.value)
  const roles = userRoleTitleList.value.map((id) => {
    return roleList.value.find((item) => item.id === id)
  })

  await updateUserRoles(props.userId, roles)
  ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
  // 通知父组件角色更新成功
  emits('updateRoles')
  closed()
}

// 获取角色列表
const roleList = ref([])
const getRoleListData = async () => {
  roleList.value = await getRoleList()
  console.log(roleList.value)
}
getRoleListData()
watchSwitchLang(getRoleListData)

const userRoleTitleList = ref([])

// 获取用户角色
const getUserRole = async () => {
  const res = await userRoles(props.userId)
  userRoleTitleList.value = res.role.map((item) => item.id)
}

watch(
  () => props.userId,
  (value) => {
    if (value) {
      getUserRole()
    }
  }
)
</script>
